import React from 'react';
import {View, Text, TouchableOpacity, KeyboardAvoidingView, Keyboard, Image} from 'react-native';
import {InputItem, Toast, Flex} from '@ant-design/react-native';
import {connect} from 'react-redux';
import {saveUserInfo} from '~/store/userinfo';
import {sendVerifyCodeForRegister, regUserForOwner} from '~/api/user';
import styles from '../styles';

const mapGetter = (state) => {
    return {
        userinfo: state.userinfo,
    };
};

const mapSetter = (dispatch) => {
    return {
        onSave: (data) => {
            dispatch(saveUserInfo(data));
        },
    };
};

const chedked = require('~/assets/confirm/tongyi2x.png');
const uncheck = require('~/assets/confirm/weitongyi2x.png');

class SignScreen extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: '',
            code: this.props.userinfo.identitycode,
            checked: false,
            time: 60,
            btnText: '获取验证码',
        };
        this.onpresss = () => {
            this.setState({
                checked: !this.state.checked,
            });
        };
    }

    setUsername = (text) => {
        this.setState({
            username: text.replace(/[^0-9]+/, ''),
        });
    };

    setPassword = (text) => {
        this.setState({
            password: text.replace(/[^0-9]+/, ''),
        });
    };

    setChecked = () => {
        this.setState({
            checked: !this.state.checked,
        });
    };

    onTimer = () => {
        var t = setInterval(() => {
            let time = this.state.time;
            if (time <= 0) {
                clearInterval(t);
                this.setState({
                    time: 60,
                    btnText: '获取验证码',
                });
            } else {
                this.setState({
                    time: --time,
                    btnText: time + 's',
                });
            }
        }, 1000);
    };

    onCode = () => {
        if (/^1[3-9]\d{9}$/.test(this.state.username)) {
            sendVerifyCodeForRegister({
                mobile: this.state.username,
                logincode: this.state.code,
                type: 2,
            }).then((r) => {
                if (r.code === 0) {
                    let time = this.state.time;
                    this.setState({
                        time: --time,
                        btnText: time + 's',
                    });
                    this.onTimer();
                    Toast.info('验证码已发送', 1);
                } else {
                    Toast.info(r.msg);
                }
            });
        } else {
            Toast.info('请输入正确的手机号码', 1);
        }
    };

    onSign = () => {
        if (/^1[3-9]\d{9}$/.test(this.state.username)) {
            regUserForOwner({
                mobile: this.state.username,
                sms: this.state.password,
                logincode: this.state.code,
                type: 2,
            }).then((r) => {
                if (r.code === 0) {
                    const data = {
                        userid: r.data.userid,
                        mobile: r.data.mobile,
                        identity: r.data.identity,
                        identityname: r.data.identityname,
                        logo: r.data.logo,
                        nickname: r.data.nickname,
                        birthday: r.data.birthday,
                        token: r.data.token,
                        code: r.data.code,
                    };
                    switch (data.identity) {
                        case 8:
                            data.owner = r.data.ownerid;
                            data.ownername = r.data.ownername;
                            break;
                        case 11:
                            data.company = r.data.companyid;
                            data.companyname = r.data.companyname;
                            data.staff = r.data.staffid;
                            data.staffname = r.data.staffname;
                            break;
                        case 21:
                            data.bank = r.data.bankid;
                            data.bankname = r.data.bankname;
                            data.staff = r.data.staffid;
                            data.staffname = r.data.staffname;
                            break;
                        case 31:
                            data.agent = r.data.agentid;
                            data.agentname = r.data.agentname;
                            data.staff = r.data.staffid;
                            data.staffname = r.data.staffname;
                            break;
                    }
                    this.props.onSave(data);
                    this.props.navigation.navigate('NavigatorTab');
                } else {
                    Toast.info('注册失败：' + r.msg);
                }
            });
        } else {
            Toast.info('请输入正确的手机号码', 1);
        }
    };

    disableCode = () => {
        return this.state.username === '' || this.state.time !== 60;
    };

    disableSubmit = () => {
        return this.state.username === '' || this.state.password === '' || !this.state.checked;
    };

    codeTextColor = () => {
        return {
            color: this.disableCode() ? 'gray' : '#EC4F46',
        };
    };

    submitButtonColor = () => {
        return {
            backgroundColor: this.disableSubmit() ? 'lightgray' : '#EC4F46',
            shadowColor: this.disableSubmit() ? 'lightgray' : '#EC4F46',
        };
    };

    render() {
        return (
            <TouchableOpacity activeOpacity={1} style={styles.mainView} onPress={() => Keyboard.dismiss()}>
                <KeyboardAvoidingView behavior="position" keyboardVerticalOffset={0}>
                    <View style={styles.titleView}>
                        <Text style={styles.titleText}>注册</Text>
                    </View>
                    <View style={styles.loginForm}>
                        <View style={styles.inputView}>
                            <InputItem
                                styles={{container: {...styles.inputText}}}
                                onSubmitEditing={() => {
                                    this.codeInput.focus();
                                }}
                                placeholder="请输入手机号"
                                placeholderTextColor="gray"
                                maxLength={11}
                                type="number"
                                value={this.state.username}
                                onChange={this.setUsername}
                            />
                        </View>
                        <View style={{...styles.inputView, ...styles.codeInput}}>
                            <InputItem
                                styles={{container: {...styles.inputText}}}
                                ref={(ref) => (this.codeInput = ref)}
                                placeholder="请输入验证码"
                                placeholderTextColor="gray"
                                type="number"
                                value={this.state.password}
                                onChange={this.setPassword}
                            />
                            <TouchableOpacity
                                activeOpacity={1}
                                style={styles.codeButton}
                                onPress={() => {
                                    if (!this.disableCode()) {
                                        this.onCode();
                                    }
                                }}>
                                <Text style={{...styles.codeText, ...this.codeTextColor()}}>{this.state.btnText}</Text>
                            </TouchableOpacity>
                        </View>
                        <Flex onPress={this.setChecked} style={styles.agreeView}>
                            <Image style={styles.agreeCheck} source={this.state.checked ? chedked : uncheck} />
                            <Text style={styles.agreeText}>同意</Text>
                            <Text
                                style={styles.agreeLink}
                                onPress={() => {
                                    this.props.navigation.push('Agreement');
                                }}>
                                《用户协议》
                            </Text>
                        </Flex>
                        <TouchableOpacity
                            activeOpacity={1}
                            style={styles.submitView}
                            onPress={() => {
                                if (!this.disableSubmit()) {
                                    this.onSign();
                                }
                            }}>
                            <View
                                style={{
                                    ...styles.submitButton,
                                    ...this.submitButtonColor(),
                                }}>
                                <Text style={styles.submitText}>注册</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </KeyboardAvoidingView>
            </TouchableOpacity>
        );
    }
}

export default connect(mapGetter, mapSetter)(SignScreen);
